package com.gupao.observerdemo.observer.core;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 事件注册和监听
 */
public class EventListener {


    protected Map<Enum,Event> events = new HashMap<>();

    /**
     *  添加监听器
     * @param eventType 事件类型
     * @param target 监听目标
     * @param callback 回调方法
     */
    public void addListener(Enum eventType, Object target, Method callback){
        events.put(eventType,new Event(target,callback));
    }


    /**
     * 触发事件
     * @param e
     */
    public void trigger(Event e){
        e.setDate(new Date());
        e.setSource(this);
        try {
            e.getMethod().invoke(e.getTarget(),e);

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }


    public void trigger(Enum eventType){

        if(this.events.containsKey(eventType)){
            Event event =this.events.get(eventType);
//            event.set;
            trigger(event);
        }
    }

}
